#!/usr/bin/python3

# T6指示灯程序

try:
    import os
    import sys
    import time
    import socket
    import threading

except ImportError:
    print(">>> lib not found !!!")
    print(">>> Please install the relevant libraries !")
    exit(1)

class GPIO:
    # 构造函数
    def __init__(self,gpio_pin):
        self.gpio_init(gpio_pin)
        
    # 析构函数
    def __del__(self):
        pass
    
    # 判断IO操作文件是否存在？是1否0
    def gpio_file_exist(self):
        ret = 99
        path = f"/sys/class/gpio/gpio{self.gpiopin}"

        if os.path.isdir(path):
            print(f">>> gpio{self.gpiopin} 文件存在")
            ret = 1
        else:
            print(f">>> gpio{self.gpiopin} 文件不存在")
            ret = 0
        return ret

    # 初始化函数
    def gpio_init(self,gpio_pin):
        self.gpiopin=gpio_pin
        # 判断是否存在，不存在则创建
        if self.gpio_file_exist()==1: # 查询
            print(">>> gpio is inited! ")
        else:
            # 创建对应的脚本控制文件
            os.system(f"echo {self.gpiopin} > /sys/class/gpio/export") 
            os.system(f"ls -l /sys/class/gpio/ | grep gpio{self.gpiopin}") # 查看

    # 获取当前IO方向
    # 0 in
    # 1 out
    def get_gpio_direction(self):
        if self.gpio_file_exist()==1:
            # 存在
            with open(f"/sys/class/gpio/gpio{self.gpiopin}/direction", "r") as f:
                direction = f.read().strip()
            
            if direction == "out":
                # out
                return 1
            elif direction == "in":
                # in
                return 0
            else:
                print(">>> IO direction:%s"%direction)
        else:
            print("GPIO file not found.", file=sys.stderr)
            return 99
            
    # 设置IO方向
    # 输入参数为0 in或1 out
    def gpio_direction(self,direction):
        if self.get_gpio_direction() != direction:
            with open(f"/sys/class/gpio/gpio{self.gpiopin}/direction", "w") as f:
                if direction != 0:
                    f.write("out")
                else:
                    f.write("in")

        with open(f"/sys/class/gpio/gpio{self.gpiopin}/direction", "r") as f:
            current_direction = f.read().strip()
        print(">>> set gpio_pin is {} mode,direction={}".format(current_direction, direction))
    

    # 获取当前电平值
    def get_gpio_outvalue(self):
        if self.gpio_file_exist(self.gpiopin):
            # 存在
            with open(f"/sys/class/gpio/gpio{self.gpiopin}/value", "r") as file:
                value = file.read()
            return int(value)
        else:
            return 99

    # 设置GPIO的输出电平
    def gpio_outvalue(self,outlevel):
        with open(f"/sys/class/gpio/gpio{self.gpiopin}/value", "w") as f:
            f.write(str(outlevel))

####################################################################

def check_ip(ip, result_var):
    try:
        # 创建socket对象
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 设置超时时间为1秒
        s.settimeout(1)
        # 尝试连接IP的端口，如果连接成功则表示IP在线
        s.connect((ip, 80))
        # 设置result_var为1表示在线
        result_var = 1
    except socket.error:
        # 设置result_var为0表示不在线
        result_var = 0
    finally:
        # 关闭socket连接
        s.close()

def check_port(ip,port):
    global Device_state
    
    while(True):
    
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex((ip, port))
        if result != 0:
            Device_state =1
            print(">>> 连接不成功，设备不在线，%d" % Device_state)
        else:
            Device_state = 99
        sock.close()
        
        time.sleep(10)

def state1(result_var):
    pass
def state2(result_var):
    pass
def state3(result_var):
    pass

# 主函数语句
if __name__ == "__main__":
    
    # T6指示灯：GPIO3_B2 3*32+1*8+2=106
    gpio_pin=106 # 
    Device_state = 0
    
    # 默认状态
    time_H = 3  # 亮灯时长
    time_L = 1  # 灭灯时长
    
    # 初始化
    gpio = GPIO(gpio_pin)
    
    # 设置方向:输出
    gpio.gpio_direction(1)
    
    # 设置值：高电平1
    gpio.gpio_outvalue(0)
    
    # 创建检测线程
    thread_OPIzero2 = threading.Thread(target=check_port,args=("10.222.222.102",22))
    thread_OPIzero2.start()

    
    #状态循环
    while(True):
        
        # 判断状态部分(该方式存在漏洞：只允许一个错误发生……)
        # 
        print(Device_state)
        if Device_state == 1:
            time_H=0.1
            time_L=0.05
        elif Device_state == 2:
            time_H=3
            time_L=3
        elif Device_state == 3:
            time_H=1
            time_L=1
        elif Device_state == 4:
            time_H=1
            time_L=0.5
        else:
            time_H=3
            time_L=1

        
        gpio.gpio_outvalue(1)
        time.sleep(time_H) # 亮的时间
        gpio.gpio_outvalue(0)
        time.sleep(time_L) # 灭的时间
    